package com.lb.shopguide.ui.fragment.guide.order;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterTicket;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.CouponBean;
import com.lb.shopguide.event.guide.SelectCouponEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/10/18.
 * 优惠券
 */

public class FragmentSelectCoupon extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.tv_select_no_coupon)
    CheckedTextView tvNoCoupon;
    @BindView(R.id.tv_coupon_num)
    TextView tvCouponNumber;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterTicket mAdapterTicket;
    private List<CouponBean> mCouponBeanList;

    private String memberCode;
    private String type;


    public static FragmentSelectCoupon newInstance(String memberCode, String type) {
        FragmentSelectCoupon fragmentSelectCoupon = new FragmentSelectCoupon();
        Bundle bundle = new Bundle();
        bundle.putString(AppConstant.MEMBER_CODE, memberCode);
        bundle.putString(AppConstant.CHECKOUT_TYPE, type);
        fragmentSelectCoupon.setArguments(bundle);
        return fragmentSelectCoupon;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_select_ticket;
    }

    @Override
    public void initData() {
        mCouponBeanList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.MEMBER_CODE)) {
            memberCode = bundle.getString(AppConstant.MEMBER_CODE);
            sendRequestGetCouponList();
        }
        if (bundle.containsKey(AppConstant.CHECKOUT_TYPE)) {
            type = bundle.getString(AppConstant.CHECKOUT_TYPE);
        }
    }

    @Override
    public void initView() {
        ntb.setTitleText("优惠券");
        ntb.setLeftImageSrc(R.drawable.iv_back);
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });

        mRecyclerView = view.findViewById(R.id.recyclerView);
        mSwipeRefreshLayout = view.findViewById(R.id.swipeLayout);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));

        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂时没有优惠券");

        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapterTicket = new AdapterTicket(R.layout.item_ticket_item, mCouponBeanList);
        mRecyclerView.setAdapter(mAdapterTicket);

        mAdapterTicket.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CouponBean bean = mCouponBeanList.get(position);
                if (bean.getTypeCode() != AppConstant.TYPE_UNABLE_TICKET) {
                    pop();
                    EventBus.getDefault().post(new SelectCouponEvent(bean));
                } else {

                }
            }
        });
    }

    @Override
    public void finishRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void sessionOutOfDate() {
        ((GuideMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    @Override
    public String getPageTag() {
        return FragmentSelectCoupon.class.getName();
    }

    @Override
    public void onRefresh() {
        mAdapterTicket.setEnableLoadMore(false);
        if (mError) {
            mAdapterTicket.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterTicket.setEmptyView(noDataView);
                mNoData = false;
            } else {
                sendRequestGetCouponList();
            }
        }
    }

    @OnClick(R.id.tv_select_no_coupon)
    void onNoCouponClick() {
        tvNoCoupon.setChecked(true);
        pop();
        EventBus.getDefault().post(new SelectCouponEvent(null));
    }

    private void bindCoupon() {
        mAdapterTicket.setNewData(mCouponBeanList);

        tvNoCoupon.setVisibility(View.VISIBLE);
        tvCouponNumber.setVisibility(View.VISIBLE);

        tvCouponNumber.setText("有" + mCouponBeanList.size() + "个红包可用");
        SpannableString mSp = new SpannableString(tvCouponNumber.getText().toString());
        mSp.setSpan(new ForegroundColorSpan(Color.rgb(253, 91, 89)), 1, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvCouponNumber.setText(mSp);
    }

    private void bindEmpty() {
        tvCouponNumber.setVisibility(View.GONE);
        tvNoCoupon.setVisibility(View.GONE);
        mCouponBeanList.clear();
        mAdapterTicket.setNewData(mCouponBeanList);

        mNoData = true;
        onRefresh();
    }

    private void sendRequestGetCouponList() {
        mCouponBeanList = new ArrayList<>();
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonActivitys = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    if (jsonActivitys.size() != 0) {
                        for (JsonElement obj : jsonActivitys) {
                            CouponBean bean = JsonUtil.getGson().fromJson(obj, CouponBean.class);
                            mCouponBeanList.add(bean);
                        }
                        bindCoupon();
                    } else {
                        bindEmpty();
                    }
                    finishRefresh();
                }
            }
        };
        ApiMethodGuide.getCouponList(new SimpleLbObserver(listener, otherListener), memberCode, type, this, FragmentEvent.DESTROY_VIEW);
    }

}
